import CryptoJS from 'crypto-js'
/**
 * 给对象注入属性
 * @param keys 属性key数组， 如 keys = ['config', 'path'] , 则会给对象注入 object.config.path 的属性
 * @param value 属性值
 * @returns {Object}
 */
Object.defineProperty(Object.prototype, 'assignProps', {
  writable: false,
  enumerable: false,
  configurable: true,
  value: function (keys, value) {
    let props = this
    for (let i = 0; i < keys.length; i++) {
      let key = keys[i]
      if (i == keys.length - 1) {
        props[key] = value
      } else {
        props[key] = props[key] == undefined ? {} : props[key]
        props = props[key]
      }
    }
    return this
  }
})

/**  质朴长存法 by lifesinger 向后补0 */
export const pad = (num, n) => {
  var len = num.toString().length
  while (len < n) {
    num = num + '0'
    len++
  }
  return num
}

/** 加密  CryptoJS.AES*/
export function encrypt(msg, key) {
  var keys = CryptoJS.enc.Utf8.parse(key/* .length < 16 ? pad(key, 16) : key */)
  return CryptoJS.AES.encrypt(msg, keys, {
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.ECB
  }).toString()
}
/** 解密  CryptoJS.AES*/
export function decrypt(cipherText, key) {
  var keys = CryptoJS.enc.Utf8.parse(key/* .length < 16 ? pad(key, 16) : key */)
  var encryptedHexStr = CryptoJS.enc.Hex.parse(cipherText)
  var srcs = CryptoJS.enc.Utf8.stringify(encryptedHexStr)
  return CryptoJS.AES.decrypt(srcs, keys, {
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.ECB
  }).toString()
}